using System.Linq;
using Tycho.Parser.Peg;

namespace Tycho.Grammar {
    class TychoIdentifierFactory {
        public static IProduction CreateTychoIdentifierProduction () {
            IRule singleModule = new SequenceRule (new NamedRule ("module", IdentifierProduction.CreateTerminal ()), new KeywordRule (":"));
            var module = new MultipleRule (1, -1, singleModule);
            var name = new NamedRule ("identifier", IdentifierProduction.CreateTerminal ());
            var sequence = new SequenceRule (module, name);

            sequence.SetInfixInformation (new NotInfixInformation ());

            var tychoIdentifier = new NonTerminal ("identifier", sequence, new [] {"module"});
            tychoIdentifier.ResultTransform = IdentifierTransform;
            return tychoIdentifier;
        }

        private static ParseResult IdentifierTransform (ParseResult parseResult) {
            var term = (CompositeTerm) parseResult.Term;

            term.SubTerms["identifier"] = CreateStringTermFromIdentifier (term.SubTerms["identifier"]);
            var module = (ListTerm) term.SubTerms["module"];
            module.Terms = module.Terms.Select (m => (ITerm) CreateStringTermFromIdentifier (m)).ToList ();

            parseResult.Term = term;

            return parseResult;
        }

        private static StringTerm CreateStringTermFromIdentifier (ITerm id) {
            var term = (IdentifierTerm) id;
            return new StringTerm (term.Name, term.SourceInformation);
        }
    }
}